package com.net.xpay.admin.controller.admin;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.SerializationUtil;
import com.net.xpay.admin.vo.PartnerCombinationSettleRecordExportVo;
import com.net.xpay.admin.vo.PartnerCombinationSettleRecordVo;
import com.net.xpay.common.domain.partner.Partner;
import com.net.xpay.common.domain.partner.PartnerCombinationSettleRecord;
import com.net.xpay.common.enums.user.CommissionMode;
import com.net.xpay.common.manager.partner.PartnerCombinationSettleRecordManager;
import com.net.xpay.common.manager.partner.PartnerManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.model.PartnerCombinationSettleRecordAggSearchModel;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.xpay.core.utils.JxlsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/admin/partner-combination-settle-record")
@Api(tags = "运营端/合伙人收益统计", description = "后台/合伙人收益统计")
public class AdminPartnerCombinationSettleRecordController {

    @Autowired
    private PartnerCombinationSettleRecordManager partnerCombinationSettleRecordManager;

    @Autowired
    private PartnerManager partnerManager;

    @ApiOperation("搜索")
    @PostMapping("/agg-search")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ADMIN', 'partner-combination-settle-record::agg-search')")
    public ResultPagedList<PartnerCombinationSettleRecordVo> aggSearchPartnerCombinationSettleRecord(@RequestBody PartnerCombinationSettleRecordAggSearchModel searchModel) {
        List<PartnerCombinationSettleRecord> records = partnerCombinationSettleRecordManager.aggSearch(searchModel);
        long count = partnerCombinationSettleRecordManager.aggSearchCount(searchModel);

        List<PartnerCombinationSettleRecordVo> vos = BeanCopierUtil.batchCopy(PartnerCombinationSettleRecord.class, PartnerCombinationSettleRecordVo.class, records);

        for (PartnerCombinationSettleRecordVo vo : vos) {
            if (vo.getCommissionMode() == CommissionMode.COST_MODE) {
                vo.setPartnerServiceRatio(vo.getServiceRatio().subtract(vo.getCostServiceRatio()));
                vo.setPartnerBankServiceRatio(vo.getBankServiceRatio().subtract(vo.getBankCostServiceRatio()));
            }
            if (vo.getPartnerId() != null) {
                Partner partner = partnerManager.getById(vo.getPartnerId());
                vo.setPartnerName(partner.getName());
            }
        }
        return new ResultPagedList<>(vos, count, searchModel);
    }



    /**
     * 收益统计记录导出
     */
    @ApiOperation("收益统计导出")
    @GetMapping("/export")
    @PreAuthorize("hasAnyRole('ADMIN', 'partner-combination-settle-record::export')")
    public ResultData<Boolean> exportPartnerCombinationSettleRecord(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);

        PartnerCombinationSettleRecordAggSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, PartnerCombinationSettleRecordAggSearchModel.class);
        //纬度选项需要全选择
        searchModel.setSettledChecked(true);
        searchModel.setDayChecked(true);
        searchModel.setTypeChecked(true);
        searchModel.setPartnerIdChecked(true);
        searchModel.setUserIdChecked(true);
        long count = partnerCombinationSettleRecordManager.aggSearchCount(searchModel);
        if (count >= 10000L){
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "记录超过10000条，无法导出");
        }
        List<PartnerCombinationSettleRecord> list = partnerCombinationSettleRecordManager.aggList(searchModel);
        List<PartnerCombinationSettleRecordExportVo> vos = BeanCopierUtil.batchCopy(PartnerCombinationSettleRecord.class, PartnerCombinationSettleRecordExportVo.class, list);
        for (PartnerCombinationSettleRecordExportVo vo : vos) {
            if (vo.getCommissionMode() == CommissionMode.COST_MODE) {
                vo.setPartnerServiceRatio(vo.getServiceRatio().subtract(vo.getCostServiceRatio()));
                vo.setPartnerBankServiceRatio(vo.getBankServiceRatio().subtract(vo.getBankCostServiceRatio()));
            }
            vo.setServiceRatio(vo.getServiceRatio().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
            vo.setBankServiceRatio(vo.getBankServiceRatio().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
            vo.setBenefitRatio(vo.getBenefitRatio().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
            vo.setCostServiceRatio(vo.getCostServiceRatio().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
            vo.setBankCostServiceRatio(vo.getBankCostServiceRatio().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
            if (vo.getSettled()){
                vo.setSettledShow("是");
            }else {
                vo.setSettledShow("否");
            }

            if (vo.getCommissionMode().equals(CommissionMode.COST_MODE)){
                vo.setResultShow("到支付宝：" + vo.getPartnerServiceRatio().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%" + "\n" + "到卡：" + vo.getPartnerBankServiceRatio().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%");
            }else {
                vo.setResultShow(vo.getBenefitRatio() + "%");
            }
        }
        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();

        model.put("records", vos);

        String fileName = "收益统计.xlsx";
        String template = "/excel/tpl/收益统计.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }
}
